﻿using System;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media.Imaging;
using ExifLib;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Phone7.CarFinder
{
	public partial class PhotoPage : PhoneApplicationPage, INotifyPropertyChanged
	{
		private PhotoChooserTask photo = new PhotoChooserTask();

        public PhotoPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(PhotoPage_Loaded);
        }

	    void PhotoPage_Loaded(object sender, RoutedEventArgs e)
		{
			this.DataContext = this;
            Settings = WheresTheCarSettings.Instance;
            photo.ShowCamera = true;
            photo.Completed += new EventHandler<PhotoResult>(photo_Completed);
        }

		private WheresTheCarSettings _settings;
		public WheresTheCarSettings Settings
		{
			get { return _settings; }
			set
			{
				_settings = value;
				RaisePropertyChanged("Settings");
			}
		}

		private void appbar_TakePhoto_Click(object sender, EventArgs e)
		{
			photo.Show();
		}

		void photo_Completed(object sender, PhotoResult e)
		{
			if (e.TaskResult == TaskResult.OK)
			{
				using (var r = new BinaryReader(e.ChosenPhoto))
				{
					try
					{
						// Instantiate the reader
						ExifReader reader = new ExifReader(e.ChosenPhoto);

						// Extract the tag data using the ExifTags enumeration
						int cameraOrientation = -1;
						string cameraMake = "";
						string cameraModel = "";

						reader.GetTagValue<int>(ExifTags.Orientation, out cameraOrientation);
						reader.GetTagValue<string>(ExifTags.Make, out cameraMake);
						reader.GetTagValue<string>(ExifTags.Model, out cameraModel);

						MessageBox.Show(string.Format("{0} : {1} - {2}", cameraMake, cameraModel, cameraOrientation));

					}
					catch( Exception x)
					{
						//MessageBox.Show("Error decoding image: " + x.Message + "\n" + x.StackTrace);
					}

					e.ChosenPhoto.Position = 0;

					byte[] buffer = new byte[e.ChosenPhoto.Length];
					r.Read(buffer, 0, (int) e.ChosenPhoto.Length);
					SavePhoto(buffer);
				}
				
				
				this.Settings.Photo = "parking.jpg";
				this.Settings.Save();
			}
		}

		void SavePhoto(byte[] bytes)
		{
			// Create virtual store and file stream
			using (var myStore = IsolatedStorageFile.GetUserStoreForApplication())
			{
				// Encode WriteableBitmap object to a JPEG stream.
				using (var myFileStream = myStore.OpenFile("parking.jpg", FileMode.Create))
				{
					myFileStream.Write(bytes, 0, bytes.Length);
				}
			}
		}

		private void appbar_ClearPhoto_Click(object sender, EventArgs e)
		{
			Settings.Photo = null;
			this.Settings.Save();
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		protected void RaisePropertyChanged(string propertyName)
		{
			Dispatcher.BeginInvoke(() =>
			{
				if (PropertyChanged != null)
				{
					PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
				}
			});
		}
		#endregion

	}
}